import hotkeys from 'hotkeys-js'
import { ref } from 'vue'

export interface HotKey {
  keys: string[]
  preventDefault?: boolean
  handler: (keys: string, event: KeyboardEvent) => void
}

export function useKeyword({ moveFunc }: { moveFunc: Function }) {
  const keyConfigs = ref<HotKey[]>([])
  // 取消监听快捷键
  const removeHotKeys = () => {
    const keys = keyConfigs.value.map((key) => getConfigKey(key.keys))
    const key = keys.join(',')
    hotkeys.unbind(key)
  }
  function getConfigKey(keys: string[]) {
    return keys.join('+')
  }
  function initHotKeys() {
    keyConfigs.value = [
      {
        keys: ['space'],
        preventDefault: true,
        handler(keys, event) {
          moveFunc(keys, event)
        },
      },
    ]
    const keys = keyConfigs.value.map((key) => getConfigKey(key.keys))
    const key = keys.join(',')
    console.log(key)
    hotkeys(key, { keyup: true }, (event, handler) => {
      const config = keyConfigs.value.find((key) =>
        getConfigKey(key.keys).split(',').includes(handler.key),
      )
      if (config) {
        if (config.preventDefault) {
          event.preventDefault()
        }
        config.handler(handler.key, event)
      }
    })
  }

  return {
    removeHotKeys,
    initHotKeys,
  }
}
